package com.creative.xcx.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.creative.config.AppConfig;
import com.creative.core.controller.BaseController;
import com.creative.core.domain.AjaxResult;
import com.creative.core.uitls.DateUtils;
import com.creative.core.uitls.Uidutil;
import com.creative.user.domain.UserInfo;
import com.creative.user.service.UserInfoService;
import com.creative.xcx.domain.XcxLogin;
import com.creative.xcx.domain.dto.MpUserDto;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

import static com.creative.user.domain.UserInfoConstants.*;
import static com.creative.xcx.domain.constant.common.CACHE_FAVORITE_KEY;
import static com.creative.xcx.domain.constant.common.CACHE_UPLOAD_KEY;

/**
 * 小程序用户相关接口
 * 创建人: ling
 * 创建时间: 2025/01/30
 */
@RestController
@RequestMapping("/XcxUser")
public class XcxUserController extends BaseController {
    @Resource
    private UserInfoService userInfoService;

    @Resource
    private AppConfig appConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 小程序通过WeChat登录
     *
     * @param code 代码
     * @return {@link AjaxResult }
     * @author ling
     * @date 2025/02/20
     */
    @PostMapping
    public AjaxResult LoginByWeChat(@RequestBody String code) {
        if (StrUtil.isEmpty(code)) {
            return error("临时凭证为空！");
        }
        StrBuilder url = StrBuilder.create();
        url.append("https://api.weixin.qq.com/sns/jscode2session?")
                .append("appid=").append(appConfig.getXcxAppId())
                .append("&secret=").append(appConfig.getXcxAppSecret())
                .append("&js_code=").append(code)
                .append("&grant_type=authorization_code");
//        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appConfig.getXcxAppId() + "&secret=" + appConfig.getXcxAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        String result = HttpUtil.get(String.valueOf(url));
//        将返回结果转为JSON对象
        XcxLogin xcxLogin = JSONUtil.toBean(result, XcxLogin.class);
        logger.info("微信登录返回值：" + result);

//      获取用户的openId
        String openId = xcxLogin.getOpenid();
        if (StrUtil.isEmpty(openId)) {
            return error("登录失败,获取openId失败！");
        }
//      检测该id是否注册过
        UserInfo userInfo = userInfoService.selectByWXOpenId(openId);
        if (userInfo == null) {
//            未注册过，则创建一个新账号
            //      随机生成uid (10位以内)
            String uid = Uidutil.generateUid(10);
            //            使用用户的默认用户名
            UserInfo user = UserInfo.builder()
                    .wxOpenId(openId)
                    .userId(uid)
                    .mpAvatar("https://z-mytest.oss-cn-beijing.aliyuncs.com/deafultavatar.png")
                    .nickName("user" + uid.substring(0, 1) + RandomUtil.randomNumbers(4))
                    .createTime(DateUtils.getNowDate())
                    .lastLoginTime(DateUtils.getNowDate())
                    .status(STATUS)
                    .useSpace(USE_SPACE)
                    .totalSpace(TOTAL_SPACE * MB)
                    .delFlag(DEL_FLAG)
                    .build();

            //        添加用户
            userInfoService.insert(user);
//            登录该账号
            StpUtil.login(uid);

            //        更新用户的上次登录时间
            user.setLastLoginTime(DateUtils.getNowDate());
            userInfoService.update(user);
        }

        if (userInfo != null) {
            //        如果账号注册过，则直接登录该账号
            String userId = userInfo.getUserId();
            //        运用saToken 加入用户id     设置登录状态
            StpUtil.login(userId);
            //        更新用户的上次登录时间
            userInfo.setLastLoginTime(DateUtils.getNowDate());
            userInfoService.update(userInfo);
        }

//        返回前端，用户的信息和token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        String token = tokenInfo.getTokenValue();
        String userId = (String) StpUtil.getLoginId();
        UserInfo loginuserInfo = userInfoService.selectById(userId);

//        构建登录信息返回体
        MpUserDto mpUserDto = MpUserDto.builder()
                .nickName(loginuserInfo.getNickName())
                .userId(loginuserInfo.getUserId())
                .isAdmin(ArrayUtil.contains(appConfig.getAdminEmails().split(","), loginuserInfo.getEmail() == null ? "" : loginuserInfo.getEmail()))
                .avatar(loginuserInfo.getMpAvatar())
                .tokenInfo(token)
                .openId(openId)
                .build();

        StpUtil.getSession().set("MpSession" + userId, mpUserDto);
        return success(mpUserDto);
    }

    /**
     * 获取微信openId
     *
     * @param userId 用户id
     * @return {@link AjaxResult }
     * @author ling
     * @date 2025/03/04
     */
//    @GetMapping("/{userId}")
//    public AjaxResult getWeChatOpenId(@PathVariable("userId") String userId) {
//        logger.info("获取微信openId，userId:{}", userId);
//        String s = HttpUtil.get("https://mp.diandianjfb.com/web/index.getwechatuserinfo?adminId=3");
//        logger.info("获取微信openId返回值：{}", s);
//        return success();
//    }

    /**
     * 更新用户信息
     *
     * @param userInfo 用户信息
     * @return {@link AjaxResult }
     * @author ling
     * @date 2025/03/23
     */
    @PostMapping("/userInfo")
    public AjaxResult updateUserInfo(@RequestBody UserInfo userInfo) {
        logger.info("更新用户信息，userInfo:{}", userInfo);
        if (userInfo.getUserId() == null) {
            return error("更新失败，参数为空！");
        }
        return toAjax(userInfoService.update(userInfo));
    }

    /**
     * 获取用户信息
     * 收藏数和上传数
     *
     * @param userId 用户id
     * @return {@link AjaxResult }
     * @author ling
     * @date 2025/03/30
     */
    @GetMapping("/{userId}")
    public AjaxResult getUserInfo(@PathVariable("userId") String userId) {
        if (StrUtil.isEmpty(userId)) {
            return error("参数为空！");
        }
//        用户收藏的key
        String favorite_key = CACHE_FAVORITE_KEY + userId;
//        用户上传的key
        String upload_key = CACHE_UPLOAD_KEY + userId;
        logger.info("获取用户信息，userId:{}", userId);
        Long favorite_size = null;
        Long upload_size = null;
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(favorite_key))) {
//            收藏数
            favorite_size = stringRedisTemplate.opsForZSet().size(favorite_key);
        }

        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(upload_key))) {
            upload_size = stringRedisTemplate.opsForZSet().size(upload_key);
        }
//            上传数
        return Objects.requireNonNull(success()
                        .put("collect", favorite_size))
                .put("upload", upload_size);
    }
}
